/**
 * 
 * 结合AmazeUi的相关功能插件
 * 
 * 
 * 
 * 
 * @param $
 */

/**
 * 引用外部JS
 * @param {} path JS的相对路径
 */
function getScript(path) {
	document.write('<script type="text/javascript" src="' + window.rootPath + "/" + path + window.resVersion + '"></script>');
}
/**
 * 引用外部CSS
 * @param {} path CSS的相对路径
 */
function getLink(path) {
	document.write('<link type="text/css" rel="stylesheet" href="' + window.rootPath + "/" + path + window.resVersion + '" />');
}

/**
 * 引入翻译显示JS
 * 用法：
 * 在页面加载完的js调用方式 
 *  1, display("user");  2，display("user,role");
 *  3, display("user,role,confs[AD_TYPE]"), 4,display("confs[AD_TYPE|SYS_DOMAIN]") 
 *  可灵活搭配，在页面中需要翻译某类型的值， 则用上面所示进行先引用，而后在js需要翻译的地方再进行翻译取值 
 *  以上举例：confs[KEY|KEY|...] 的写法为数据配置字典的数据 
 * 在需要使用的时候： $.fn.display.display.user[数据id]取相应的翻译值，    $.fn.display.confs.AD_TYPE[field] 获取value对应的配置值（名称）。      
 * @param {} types
 */
function display(types){
    document.write('<script type="text/javascript" src="' + window.rootPath + "/displayjs?type=" + encodeURIComponent(types) + "&v=" + new Date() + '"></script>');
}

(function($){
	
	$.fn.extend({
		
		
		/**
		 * 
		 * 清除表单校验校验状态
		 * 
		 */
		amValidClear : function(){
			var $form = $(this);
			$form.find(".am-form-error,.am-form-success,.am-field-error,.am-field-valid")
				.removeClass("am-form-error").removeClass("am-form-success").removeClass("am-field-error")
				.removeClass("am-field-valid");
		},
		
		/**
		 * 
		 * 定义AmazeUi 表单校验的tooltip 样式校验 
		 * 
		 */
		amValidator : function(){
			var $form = $(this);
			var $tooltip = $('<div id="vld-tooltip">提示信息！</div>');
			$tooltip.appendTo(document.body);
			$form.validator();
			$form.find('button[type=submit]').removeClass('am-disabled').addClass("am-disabled");
			var validator = $form.data('amui.validator');

			$form.on('focusin focusout', '.am-form-error input', function(e) {
				if (e.type === 'focusin') {
			      var $this = $(this);
			      var offset = $this.offset();
			      var msg = $this.data('foolishMsg') || validator.getValidationMessage($this.data('validity'));
	
			      $tooltip.text(msg).show().css({
			        left: offset.left + 10,
			        top: offset.top + $(this).outerHeight() + 10
			      });
			    } else {
			      $tooltip.hide();
			    } 
			});
			$form.on('focusin focusout', '.am-form-success input', function(e) {
				if (e.type === 'focusout') {
					 $form.find('button[type=submit]').removeClass('am-disabled');
					 $tooltip.hide();
				}
			});
		},
		amSelectInit : function(options){
			var defaults = {
				url : null, 
				id : 'id' , 
				text : 'name' ,
				selVal : null ,
				params : {},
				showDefault : null,
				init : null
			};
			$.extend(defaults, options);
			var target = $(this);
			if(!defaults.url){return ;}
			$.post(defaults.url, defaults.params, function(r) {
				target.html('');
				if(defaults.showDefault)
					target.append(defaults.showDefault);
				for ( var i in r) {
					var opt = '<option value="'+r[i][defaults.id]+'"' ; 
					if(defaults.selVal && r[i][defaults.id] == defaults.selVal)
					opt += ' selected ';
					opt += '>'+r[i][defaults.text]+'</option>' ;
					target.append(opt);
				}
				if(defaults.init) defaults.init();
	         }, 'json');
		} ,
		amJsonToForm:function(json){
			var form = $(this);
			if($.isPlainObject(json)){
				$.each(json,function(i,n){
					var field = form.find('input[name='+i+']');
					switch (field.attr('type')) {
					case 'hidden':
						field.val(n);
						break;
					case 'text':
						field.val(n);
						break;
					case 'radio':
						field.each(function(){
							var value = $(this).val();
							if(value == 'true'){value = true;}else if(value == 'false'){value = false;}
							if(value == n){$(this).get(0).checked = true;}
							});
						break;
					case 'checkbox':
						field.each(function(){
							var value = $(this).val();
							if(value == 'true'){value = true;}else if(value == 'false'){value = false;}
							if(value == n){$(this).get(0).checked = true;}
						});
						break;
					default:
						field = form.find('select[name='+i+']');
						if(!$.isEmptyObject(field.get(0))){
							field.children('option').each(function(){
								if($(this).val() == n){this.selected = true;}
							});
						}
						field = form.find('textarea[name='+i+']');
						if(!$.isEmptyObject(field.get(0))){
							field.val(n);
						}
						break;
					}
				});
			}
		} ,amFormToJson:function(){
			var str = $(this).serialize();
				str = str.replace(/\+/g,"%20");
				str = str.replace(/&/g,"\",\"");
				str = str.replace(/=/g,"\":\"");
			var data = eval("({\""+str +"\"})");
			$.each(data,function(i,n){data[i] = $.trim(decodeURIComponent(n));});
			return data;
		},
		amPagination : function(options){
			var defaults = {
				pn : 1,
				ps : 10,
				total : 0 ,
				viewType : 'normal',
//				align:'center',
				isload:false,
				selectPage: null
			}
			
			$.extend(defaults, options || {});
			var target=$(this),targetId=$(this).attr("id");
			function _init(){
				var _pageHtml = "<div class='am-align-right am-margin-right'><ul class='am-pagination' id='"+targetId+"_page_ul'>";
				switch(defaults.viewType){
				case 'easy':
					break;
				case 'normal':
					var _page_li = parseInt((defaults.total%defaults.ps==0) ? (defaults.total/defaults.ps) : (defaults.total / defaults.ps +1)) ;
					_page_li = _page_li == 0 ? 1 : _page_li ;
					
					_pageHtml += '<li class="'+(defaults.pn-1==0? "am-disabled" : "")+'"><a href="javascript:void(0)" data-pn="1">&laquo;</a></li>';
					for (var i = 1; i <= _page_li; i++) {
						_pageHtml += '<li class="'+(i==defaults.pn?'am-active' : '')+'"><a href="javascript:void(0)" data-pn="'+i+'">'+i+'</a></li>';
					}
					console.info(defaults.pn +"|"+ _page_li);
					_pageHtml += '<li class="'+(defaults.pn==_page_li ? "am-disabled" : "")+'"><a href="javascript:void(0)" data-pn="'+_page_li+'" >&raquo;</a></li>';
					break;
				default :
					break;
				}
				_pageHtml += "</ul></div>";
				target.html(_pageHtml);
				$('#'+targetId+'_page_ul li:not(.am-active) a').click(function(){
					if(defaults.selectPage){
						defaults.selectPage($(this).data("pn"));
					}
				});
			}
			_init();
		},
		/* 数据表格插件*/
		amDataGrid:function(options,params){
			var defaults = {
				pagination : false,
				pageSize : 10,
				pageList:[10,20,30,50,100],
				queryParams : {},
				url : null,
				isload : false,
				pn:1,
				pageSetting :{
					total : true,
					pageList:true,
					type : 'ul'
				}
			};
			var default_fmt = {
				amNo : function(_amValue,_amRowData,_amIndex){
					var pn =  1 , ps = defaults.pageSize ;
					pn = gData.defaults ? gData.defaults.pn : pn ;
					ps = gData.defaults ? gData.defaults.pageSize : ps ;
					return ((pn-1)*ps + _amIndex +1)  ;
				},
				amCk : function(_amValue,_amRowData,_amIndex){
					var pchk = target.find("thead input[type='checkbox']");
					var chk = "<input type='checkbox' name='"+(pchk.length>0 ? $(pchk[0]).attr('name') : 'amCk')+"' value='"+_amIndex+"'/>";
					return chk;
				}
			};
			var dom_event = {
				pl_sel : function(val,target){
					$('#'+target).html(val);
					defaults.pageSize = val  ;
					_loadData();
				}
			};
			 
			
			var target=$(this),targetId=$(this).attr("id");
			var gData = target.data("data") || {};
			$.extend(defaults, options || {});
			defaults.isload = target.data('isload');
			function trFmt(_amIndex,_amData){
				var h_ths = target.find('thead > tr > th,head > tr > td');
				var tr0 = "<tr>";
				for ( var i = 0 ;i < h_ths.length ;i++) {
					eval('var opt = {'+$(h_ths[i]).data("options")+'}') ;
					tr0 += "<td class='"+(opt.amClass || '')+" title='"+(_amData[opt.field]||'')+"'>";
					switch(opt.field){
					case 'amCk':
						opt.formatter = default_fmt.amCk ;
						break;
					case 'amNo':
						opt.formatter = default_fmt.amNo ;
						break;
					}
					if(opt.formatter != null ){
						tr0 += opt.formatter(_amData[opt.field]||'', _amData, _amIndex);
					}else{
						tr0 += _amData[opt.field]||'' ;
					}
					tr0 += "</td>";
				}
				tr0 += "</tr>";
				return tr0;
			}
			function _dataView(_amData,_flag){
				var rows = _amData.rows;
				var h_ths = target.find('thead > tr > th,thead >tr > td');
				var tbody = "<tbody>";
				for ( var i in rows) { tbody += trFmt(parseInt(i),rows[i]); }
				tbody += "</tbody>";
				if($("#"+targetId +" tbody").size()>0) $(tbody).replaceAll("#"+targetId +" tbody");
				else $("#"+targetId).append(tbody);
				if(_flag){
					_pageView(_amData.total);
				}
				target.find("thead input[type='checkbox']").click(function(){
					var checked = this.checked;
					target.find("tbody input[type='checkbox']").each(function(){
						this.checked = checked ;
					});
				});
				iframeReSize();
			}
			function _pageView(_amTotal){
				if($("#"+targetId+"_pagination").length > 0) {
					$("#"+targetId+"_page_total").html(_amTotal);
				}else{
					var pageHtml = "<div class='am-cf'>";
					pageHtml += " </select></div></div><div id='"+targetId+"_pagination'></div></div>";
					pageHtml += "<div class='am-u-md-4 am-u-sm-16 am-u-end'>共  <span id='"+targetId+"_page_total'>"+_amTotal+"</span> 条记录  " ;
					pageHtml += '<span id="'+targetId+'_page_dropdown_select">';
					pageHtml += '<span class="am-dropdown am-dropdown-up am-margin-horizontal" id="'+targetId+'_page_dropdown_list">';
					pageHtml += '每页显示 <a class="am-dropdown-toggle am-link" href="javascript:void(0);" id="'+targetId+'_page_dropdown_list_a"> '+defaults.pageSize+'</a> 条 ';
					pageHtml += '<ul class="am-dropdown-content">';
					for (var i = 0; i < defaults.pageList.length; i++) {
						pageHtml += '<li><a href="javascript:void(0);">'+defaults.pageList[i]+'</a></li>';
					}
					pageHtml += '</ul><span></span>';
					pageHtml += "</div></div>";
					target.after(pageHtml);
					$('#'+targetId+"_page_dropdown_list").dropdown({justify: '#'+targetId+'_page_dropdown_select'});
					$('#'+targetId+"_page_dropdown_list ul li a").each(function(i){
						$(this).click(function(){
							$('#'+targetId+"_page_dropdown_list").dropdown('close');
							dom_event.pl_sel($(this).text(),targetId+"_page_dropdown_list_a");
						});
					});
				}
				$("#"+targetId+"_pagination").amPagination({
						total:_amTotal,pn:defaults.pn,ps:defaults.pageSize,
						selectPage:function(value){
							console.info(value);
							defaults.pn = value;
							_loadData();
						}
					});
			}
			function _loadData(){
				defaults.queryParams.rows=defaults.pageSize;
				defaults.queryParams.page = (defaults.pn||1);
//				+= "&rows="+defaults.pageSize+"&page="+;
				if(defaults.url==null || defaults.url == '') return ;
				$.ajax({
					   type: "POST",
					   url: defaults.url,
					   data: defaults.queryParams,
					   dataType:'json',
					   success: function(r){
						   var maxPage = parseInt((r.total%defaults.pageSize==0) ? (r.total/defaults.pageSize) : (r.total / defaults.pageSize +1)) ;
						   if(r.total != 0 && defaults.pn > maxPage ){
							   defaults.pn = maxPage;
							   _loadData();
						   }
						   _dataView(r,defaults.pagination);
						   defaults.isload = true ;
						   gData.defaults = defaults;
						   gData.data = r ;
						   target.data('isload',true);
						   target.data('data',gData);
					   },
					   error:function(XMLHttpRequest, status){
						   console.info(status);
					   }
					});
			}
			if (typeof options == "string") {
				switch(options){
					case 'refresh':
						defaults = gData.defaults ;
						_loadData();
						break;
					case 'reload' : 
						_dataView(gData.data,gData.defaults.pagination);
						break;
					case 'load' : 
						defaults = gData.defaults ;
						defaults.queryParams = params || {};
						_loadData();
						break;
					case 'getRows' : 
						return gData.data.rows;
						break;
					case 'getSelectRows' :
						if(params){
							var rows = new Array();
							$("#"+targetId +" tbody td input[type=checkbox]:checked").each(function(i){
								rows.push(gData.data.rows[$(this).val()]);
							});
							params(rows);
						}
						break;
					case 'selectRow' :
						if(params){
							$("#"+targetId +" tbody td input[type=checkbox][value='"+params+"']").each(function(i){
								this.checked = true ;
							});
						}
					break ;
					default :
						console.info('控件未提供该方法');
				}
			}
			if(!defaults.isload)
				_loadData();
			return target ;
		}
	});
})(jQuery);


function iframeReSize(){
	
	if(window.top != window.self){
		
		var width = $('body').width();
		var height = $('body').height()-2;
		
		var bHeight = window.top.$('#topbar:visible').height() || 0;
		var mWidth = window.top.$('#admin-menus:visible').width() || 0;
		var tHeight = window.top.innerHeight - bHeight;
		var tWidth = window.top.innerWidth;
		//console.info(width +"|" +height+"|t:" +tHeight);
		//top.$('#show_remark').html(width +"|" +mWidth+"|tw:"+(tWidth)+"|th:" +tHeight );
		if(height < tHeight ){
			height = tHeight ;
		}
		window.top.$('#rightIframe').css({width:(tWidth-mWidth-1)+'px', height:height+'px'});
		
	}else{ 
		var mWidth = $('#admin-menus:visible').width() || 0;
		var bheight = $('#topbar:visible').height() || 0;
		var width = $('body').width() - mWidth -2;
		var height = $('body').height() - bheight -2;
		//console.info(width +"|" +height +"|bheight " + bheight);
		$('#rightIframe').css({width:width+'px', height:height+'px'});
	}
}

$(function(){
	
	if(window.top != window.self){
		iframeReSize(); 
	}else{
		iframeReSize();
		$(window).resize(function(){
			iframeReSize()
		});
	}
	
	
});



